<template>
  <div class="login flex js-ct">
    <div class="box">
      <div class="title text-30 share-color">{{ $t("newTheme.welcome") }}</div>
      <div class="login-box radius second-bg">
        <div class="tab text-14 flex js-ct point">
          <div
            class="tab-box text-ellipsis"
            :class="state.tabid === 1 ? 'tabactive text-t1' : 'text-t2'"
            @click="changeTab(1)"
          >
            {{ $t("login.loginWithPhone") }}
          </div>
          <div
            class="tab-box text-ellipsis"
            :class="state.tabid === 2 ? 'tabactive text-t1' : 'text-t2'"
            @click="changeTab(2)"
          >
            {{ $t("login.loginWithEmail") }}
          </div>
        </div>
        <el-form
          ref="ruleForm"
          :model="state.loginParam"
          :rules="state.rules"
          class="demo-ruleForm"
        >
          <el-form-item label prop="user_email" v-if="state.tabid === 2">
            <el-input
              v-model="state.loginParam.user_email"
              :placeholder="$t('login.emailTip')"
              @blur="testRemeberPassword"
              @input="clearPassword"
            ></el-input>
          </el-form-item>
          <el-form-item label prop="user_phone" v-if="state.tabid === 1">
            <el-input
              v-model="state.loginParam.user_phone"
              :placeholder="$t('login.phoneTip')"
              @blur="testRemeberPassword"
              @input="clearPassword"
            ></el-input>
          </el-form-item>
          <el-form-item label prop="user_password">
            <el-input
              class="password"
              ref="password"
              v-model="state.loginParam.user_password"
              :type="state.passwordType"
              @focus="clearPassword"
              :placeholder="$t('login.passwordTip')"
            >
              <template #suffix>
                <span class="show-pwd" @click="showPwd($event)">
                  <svg-icon
                    :data_iconName="
                      state.passwordType === 'password'
                        ? 'ic_eye'
                        : 'ic_eye_open'
                    "
                  />
                </span>
              </template>
            </el-input>
          </el-form-item>

          <div class="flex align-center js-sp mg-bt-30">
            <div class=" text-left">
              <router-link
                class="text-t1 text-14 text-bold"
                to="/forgotPassword"
                >{{ $t("login.forgetPass") }}?</router-link
              >
            </div>
            <div v-if="remember_password">
              <el-checkbox
                v-model="remember"
                :label="$t('login.rememberPassword')"
                size="large"
              />
            </div>
          </div>
          <div class="mg-bt-xs">
            <el-button
              style="width:100%;height:46px"
              @click="toLogin"
              class="login-btn share-color"
              >{{ $t("login.login") }}</el-button
            >
          </div>
          <div class="flex js-ed">
            <div class="text-right text-14 text-t2">
              {{ $t("login.noAccount") }}?
              <router-link
                to="/register"
                class="text-login text-14 font-weight"
                >{{ $t("register.register") }}</router-link
              >
            </div>
          </div>
        </el-form>
      </div>
    </div>
  </div>
</template>

<script>
import { reactive, ref, nextTick, onMounted, onBeforeMount } from "vue";
import { useStore } from "vuex";
import { useRoute, useRouter } from "vue-router";
import { ElMessage } from "element-plus";
import { passwordRule, emailRule, phoneRule } from "@/utils/formValidation";
import { useI18n } from "vue-i18n";
import { Base64 } from "js-base64";
import UseSystemSetting from "@/commonapi/useSystemSetting";
export default {
  setup() {
    const { t } = useI18n();
    var EmailRule = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("*" + t("formTip.emailTip")));
      } else {
        if (!emailRule.reg.test(value)) {
          callback(new Error("*" + emailRule.message));
        } else {
          callback();
        }
      }
    };
    var PhoneRule = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("*" + t("formTip.phoneTip")));
      } else {
        if (!phoneRule.reg.test(value)) {
          callback(new Error("*" + phoneRule.message));
        } else {
          callback();
        }
      }
    };
    var PassRule = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("*" + this.$t("formTip.passwordTip")));
      } else {
        callback();
        //先隐藏
        // if (!passwordRule.reg.test(value)) {
        //   callback(new Error("*" + passwordRule.message));
        // } else {
        //   callback();
        // }
      }
    };
    const state = reactive({
      tabs: ["手机登录", "邮箱登录"],
      tabid: 1,
      clientH: 0,
      loginParam: {
        login_device: "pc",
      },
      rules: {
        user_phone: [{ validator: PhoneRule, trigger: "blur" }],
        user_email: [{ validator: EmailRule, trigger: "blur" }],
        user_password: [{ validator: PassRule, trigger: "blur" }],
      },
      passwordType: "password",
    });
    // 获取开关状态
    const { remember_password } = UseSystemSetting();
    // methods
    const $store = useStore();
    const $router = useRouter();
    const $route = useRoute();
    const ruleForm = ref(null);
    const password = ref(null);
    const showPwd = (event) => {
      if (state.passwordType === "password") {
        state.passwordType = "text";
      } else {
        state.passwordType = "password";
      }
      // nextTick(() => {
      //   password.value.focus();
      // });
      event.stopPropagation();
    };
    const toLogin = () => {
      let param = state.loginParam;
      param.login_type =param.loginType==1?"mobile":"email";
      param.loginType = state.tabid;
      if (param.loginType === 1) {
        param.user_email = "";
      } else {
        param.user_phone = "";
      }
      
      param.area_id=2;
      param.account=param.user_email;
      param.password=param.user_password;
      ruleForm.value.validate((valid) => {
        if (valid) {
          $store
            .dispatch("user/login", param)
            .then(() => {
              let temp = $store.state.user?.systemInfo.find((item) => {
                return item.key === "virtual_wallet";
              });
              $store.commit("user/SET_VIRTUAL_WALLET", false);
              console.log("是否开启模拟账户", temp?.value);
              setUserInfo();
              if (param.loginType) {
                if (param.loginType === 1) {
                  localStorage.removeItem("email");
                } else {
                  localStorage.removeItem("phone");
                }
              }
              nextTick(() => {
                const route = $route.query.redirect || "/";
                $router.push(route);
              });
            })
            .catch((err) => {
              ElMessage.error(err);
            });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    };
    // 切换登录方式
    const changeTab = (i) => {
      state.tabid = i;
      state.loginParam.user_password = "";
      // state.loginParam = {
      //   login_device: "pc"
      // };
      state.account = "";
    };
    onMounted(() => {
      state.clientH = window.innerHeight;
    });
    //记住密码
    const remember = ref(false);
    const testRemeberPassword = () => {
      if (localStorage.getItem("rememberArr")) {
        let rememberArr = JSON.parse(localStorage.getItem("rememberArr"));
        if (rememberArr.length > 0) {
          let accountRes = rememberArr.findIndex((ele) => {
            return (
              ele.account ==
              (state.tabid == 2
                ? state.loginParam.user_email
                : state.loginParam.user_phone)
            );
          });
          if (accountRes > -1) {
            state.loginParam.user_password = Base64.decode(
              rememberArr[accountRes].password
            );
            remember.value = true;
          }
        }
      }
    };
    onBeforeMount(() => {
      let phone = localStorage.getItem("phone");
      let email = localStorage.getItem("email");

      if (phone) {
        state.tabid = 1;
        state.loginParam.user_phone = phone;
      } else if (email) {
        state.tabid = 2;
        state.loginParam.user_email = email;
      }

      if (localStorage.getItem("rememberArr")) {
        let rememberArr = JSON.parse(localStorage.getItem("rememberArr"));
        if (rememberArr.length > 0) {
          let accountRes = rememberArr.findIndex((ele) => {
            return (
              ele.account ==
              (state.tabid == 2
                ? state.loginParam.user_email
                : state.loginParam.user_phone)
            );
          });
          if (accountRes > -1) {
            state.loginParam.user_password = Base64.decode(
              rememberArr[accountRes].password
            );
            remember.value = true;
          }
        }
        // let account = localStorage.getItem("account");
        // let password = Base64.decode(localStorage.getItem("password"));
        // console.log(account, password, state.loginParam.user_email == account);
        // if (
        //   account &&
        //   (state.loginParam.user_email == account ||
        //     state.loginParam.user_phone == account)
        // ) {
        //   state.loginParam.user_password = password;
        //   remember.value = true;
        //   // state.passwordType = "password";
        // }
      }
    });
    const setUserInfo = () => {
      let rememberArr = localStorage.getItem("rememberArr")
        ? JSON.parse(localStorage.getItem("rememberArr"))
        : [];
      let accountRes = rememberArr.findIndex((ele) => {
        return (
          ele.account ==
          (state.tabid == 2
            ? state.loginParam.user_email
            : state.loginParam.user_phone)
        );
      });
      if (remember.value == true) {
        let obj = {
          account:
            state.tabid == 2
              ? state.loginParam.user_email
              : state.loginParam.user_phone,
          password: Base64.encode(state.loginParam.user_password),
        };
        if (accountRes > -1) {
          rememberArr.splice(accountRes, 1, obj);
        } else {
          rememberArr.push(obj);
        }

        localStorage.setItem("rememberArr", JSON.stringify(rememberArr));
      } else {
        if (accountRes > -1) {
          rememberArr.splice(accountRes, 1);
        }
        localStorage.setItem("rememberArr", JSON.stringify(rememberArr));
      }
    };
    const clearPassword = () => {
      if (state.loginParam.user_password) {
        state.loginParam.user_password = "";
      }
    };
    return {
      state,
      changeTab,
      toLogin,
      ruleForm,
      EmailRule,
      PhoneRule,
      PassRule,
      showPwd,
      password,
      remember,
      remember_password,
      clearPassword,
      setUserInfo,
      testRemeberPassword,
    };
  },
};
</script>
<style lang="less" scoped>
.login {
  width: 100%;
  height: calc(100% - 60px);
  position: fixed;
  top: 60px;
  left: 0;
  // height: 800px;
  padding-top: 55px;
  background-image: url("../assets/theme1/loginbg.png");
  background-repeat: no-repeat;
  background-size: 100% 100%;
  box-sizing: border-box;
}
.mb-20 {
  margin-bottom: 20px;
}
.mb-30 {
  margin-bottom: 30px;
}
.mb-10 {
  margin-bottom: 10px;
}
.mt-55 {
  margin-top: 55px;
}
.font-weight {
  font-weight: bold;
}
.login-box {
  width: 400px;
  // height: 425px;
  padding: 30px;
  box-sizing: border-box;
}
.title {
  font-family: PingFang SC;
  margin-bottom: 40px;
  font-style: Semibold;
}
.tab {
  line-height: 40px;
  min-height: 40px;
  margin-bottom: 20px;
}
.phone {
  margin-inline-end: 30px;
}
.tabactive {
  position: relative;
  font-weight: bold;
  font-family: PingFang SC;
  font-style: Semibold;
  background: @tab-active;
}
.show-pwd {
  display: inline-block;
  position: absolute;
  right: 10px;
  // top: 7px;
  font-size: 16px;
  color: #889aa4;
  cursor: pointer;
  user-select: none;
}
.tab-box {
  width: 170px;
  height: 40px;
  text-align: center;
  border-radius: 4px;
  padding: 0 4px;
}
.password ::-ms-reveal {
  display: none;
}
// .tabactive::after {
//   content: "";
//   position: absolute;
//   bottom: 0;
//   left: 0;
//   width: 44px;
//   height: 4px;
//   background: @login-dark;
//   border-radius: 4px;
// }
.login /deep/.el-input__inner:hover {
  border-color: #f8f8f8;
}
.login /deep/.el-input__inner {
  border: 1px solid #f8f8f8;
}
.login {
  :deep(.el-checkbox__input.is-checked
      .el-checkbox__inner, .el-checkbox__input.is-indeterminate
      .el-checkbox__inner) {
    background-color: @blue;
    border-color: @blue;
  }
  :deep(.el-checkbox__input.is-checked + .el-checkbox__label) {
    color: @blue;
  }
  :deep(.el-checkbox__inner:hover) {
    border-color: @blue;
  }
}
</style>
